﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace PhotoViewer
{
    public partial class frmPictureMax : Form
    {
        public frmPictureMax()
        {
            InitializeComponent();
        }

        #region 窗体最大化类字段

        public string imagePath; //某个图片的路径
        public string pictureWidth; //图片的宽度
        public string pictureHeight;    //图片的高度
        public double selectFileSize;   //图片的尺寸

        //bool isDrag = false; //用于标识是否拖动鼠标
        //Point startPoint;//记录开始绘制位置
        //Rectangle rectangle;
        //Bitmap cropBmp;
        private bool selected;
        private Rectangle selection;
        Bitmap cropBmp;


        #endregion

        /// <summary>
        /// 加载窗体显示图片信息以及图片的最大化显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmPictureMax_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            Image image = Image.FromFile(imagePath);

            this.Width = Convert.ToInt32(image.Width);
            this.Height = Convert.ToInt32(image.Height);

            try
            {
                pictureBox1.Image = Image.FromFile(imagePath);//显示图片

                //窗体的text位置显示图片的路径信息、图片的像素，以及图片的大小
                this.Text = imagePath + "   " + "(" + pictureWidth + "×" + pictureHeight + ")" + "   " + "[" + selectFileSize.ToString("F") + "M]";
            }
            catch
            {
                this.Close();
            }
        }

        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            this.Close();
        }




        private void btnCrop_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.Cross;
        }


        //private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
        //{
        //    if (e.Button == MouseButtons.Left)//按下鼠标左键触发该事件
        //    {
        //        selected = true;
        //        selection = new Rectangle(new Point(e.X, e.Y), new Size());
        //    }
        //}

        //private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        //{
        //    // Update the actual size of the selection:
        //    if (selected)
        //    {
        //        selection.Width = e.X - selection.X;
        //        selection.Height = e.Y - selection.Y;

        //        // Redraw the picturebox:
        //        pictureBox1.Refresh();
        //    }

        //}

        //private void pictureBox1_Paint(object sender, PaintEventArgs e)
        //{
        //    if (selected)
        //    {
        //        // Draw a rectangle displaying the current selection
        //        Pen pen = Pens.GreenYellow;
        //        e.Graphics.DrawRectangle(pen, selection);
        //    }
        //}

        //private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        //{
        //    if (e.Button == MouseButtons.Left && selected && selection.Size != new Size())
        //    {
        //     selected = false; 
        //        //// Create cropped image:
        //        //Bitmap bmp = new Bitmap(pictureBox1.Image);
        //        //// Crop the image:
        //        //cropBmp = bmp.Clone(selection, bmp.PixelFormat);
        //        // Create cropped image:
        //        Image img = ImageOperate.Crop(this.pictureBox1.Image, selection);

        //        // Fit image to the picturebox:
        //        pictureBox1.Image = ImageOperate.Fit2PictureBox(img, pictureBox1);
        //    }
        //    else 
        //        selected = false;

        //    //this.Cursor = Cursors.Default;
        //}

        /// <summary>
        /// 图片放大功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEnlarge_Click(object sender, EventArgs e)
        {
            //设置放大的倍数
            double scale = 1.2;
            this.pictureBox1.Width =Convert.ToInt32(this.pictureBox1.Width * scale);
            this.pictureBox1.Height =Convert.ToInt32( this.pictureBox1.Height * scale);
        }

        /// <summary>
        /// 图片缩小功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNarrow_Click(object sender, EventArgs e)
        {
            double narrowScale = 0.5;
            this.pictureBox1.Width = Convert.ToInt32(this.pictureBox1.Width * narrowScale);
            this.pictureBox1.Height = Convert.ToInt32(this.pictureBox1.Height * narrowScale);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //过滤器声明由说明|后缀名组成
                saveFileDialog1.Filter = "BMP|*.bmp|JPEG|*.jpeg|GIF|*.gif|PNG|*.png";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string picPath = saveFileDialog1.FileName;//为文件保存的路径

                    string picType = picPath.Substring(picPath.LastIndexOf(".") + 1, picPath.Length - picPath.LastIndexOf(".") - 1);    //获取文件的后缀名

                    //将图片保存为相应的格式
                    switch (picType)
                    {
                        case "bmp":
                            //将源文件imagepath保存到新路径
                            Bitmap bitMap = new Bitmap(cropBmp);
                            cropBmp.Save(picPath, System.Drawing.Imaging.ImageFormat.Bmp);
                            break;
                        case "jpeg":
                            Bitmap jpgMap = new Bitmap(cropBmp);
                            cropBmp.Save(picPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            break;
                        case "gif":
                            Bitmap gifMap = new Bitmap(cropBmp);
                            cropBmp.Save(picPath, System.Drawing.Imaging.ImageFormat.Gif);
                            break;
                        case "png":
                            Bitmap pngMap = new Bitmap(cropBmp);
                            cropBmp.Save(picPath, System.Drawing.Imaging.ImageFormat.Png);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        //private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        //{
        //    //用白色填充剪切掉的部分
        //    Graphics graphics = pictureBox1.CreateGraphics();
        //    SolidBrush brush = new SolidBrush(Color.White);
        //    graphics.FillRectangle(brush, selection);
        //}

    }


    public class ImageOperate
    {
        /// <summary>
        /// Crops an image according to a selection rectangel
        /// </summary>
        /// <param name="image">
        /// the image to be cropped
        /// </param>
        /// <param name="selection">
        /// the selection
        /// </param>
        /// <returns>
        /// cropped image
        /// </returns>
        public static Image Crop( Image image, Rectangle selection)
        {
            Bitmap bmp = image as Bitmap;

            // Check if it is a bitmap:
            if (bmp == null)
                throw new ArgumentException("No valid bitmap");

            // Crop the image:
            Bitmap cropBmp = bmp.Clone(selection, bmp.PixelFormat);

            // Release the resources:
            image.Dispose();

            return cropBmp;
        }

        /// <summary>
        /// Fits an image to the size of a picturebox
        /// </summary>
        /// <param name="image">
        /// image to be fit
        /// </param>
        /// <param name="picBox">
        /// picturebox in that the image should fit
        /// </param>
        /// <returns>
        /// fitted image
        /// </returns>
        /// <remarks>
        /// Although the picturebox has the SizeMode-property that offers
        /// the same functionality an OutOfMemory-Exception is thrown
        /// when assigning images to a picturebox several times.
        /// 
        /// AFAIK the SizeMode is designed for assigning an image to
        /// picturebox only once.
        /// </remarks>
        public static Image Fit2PictureBox( Image image, PictureBox picBox)
        {
            Bitmap bmp = null;
            Graphics g;

            // Scale:
            double scaleY = (double)image.Width / picBox.Width;
            double scaleX = (double)image.Height / picBox.Height;
            double scale = scaleY < scaleX ? scaleX : scaleY;

            // Create new bitmap:
            bmp = new Bitmap(
                (int)((double)image.Width / scale),
                (int)((double)image.Height / scale));

            // Set resolution of the new image:
            bmp.SetResolution(
                image.HorizontalResolution,
                image.VerticalResolution);

            // Create graphics:
            g = Graphics.FromImage(bmp);

            // Set interpolation mode:
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            // Draw the new image:
            g.DrawImage(
                image,
                new Rectangle(            // Destination
                    0, 0,
                    bmp.Width, bmp.Height),
                new Rectangle(            // Source
                    0, 0,
                    image.Width, image.Height),
                GraphicsUnit.Pixel);

            // Release the resources of the graphics:
            g.Dispose();

            // Release the resources of the origin image:
            image.Dispose();

            return bmp;
        }
    
    }
}
